package com.xiangyi.teachingsystem.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiangyi.teachingsystem.entity.po.User;
import com.xiangyi.teachingsystem.entity.vo.Result;
import com.xiangyi.teachingsystem.service.UserService;
import com.xiangyi.teachingsystem.validation.groups.AdminOperUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/userOper")
public class AdminUserController {
    @Autowired
    UserService userService;

    @GetMapping("/userList")
    public Result userList(){
        List<User> userList = userService.getBaseMapper().selectList(new QueryWrapper<User>()
                .eq("admin_sign", false));
        return Result.success("用户列表查询成功").setData(userList);
    }

    @GetMapping("/delUser")
    public Result deluser(@RequestParam Integer userId){
        try {
            User userInfo = userService.getById(userId);
            if (userInfo!=null){
                userService.remove(new QueryWrapper<User>()
                        .eq("id",userId)
                        .eq("admin_sign",false));
                return Result.success("用户移除成功").setData(userInfo);
            }
            return Result.failure("用户不存在");
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器异常").setData(e.getMessage());
        }
    }

    @PostMapping("/addOrUpdateUser")
    public Result addOrUpdateuser(@Validated(AdminOperUser.class) @RequestBody User user){
        String phoneNum = user.getPhoneNum();
        User userInfo = userService.getOne(new QueryWrapper<User>()
                .eq("phone_num", phoneNum)
                .eq("admin_sign",false));
        if (user.getId()!=null){
            userService.update(user,new UpdateWrapper<User>()
                    .eq("id",user.getId())
                    .eq("admin_sign",false));
            return Result.success("用户信息更新成功");
        }
        if (userInfo==null){
            user.setAdminSign(false);
            userService.save(user);
            return Result.success("用户添加成功");
        }else {
            return Result.failure("手机号已存在");
        }

    }
}
